package com.ruoyi.app.controller

import cn.hutool.core.util.ObjectUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.shaun.core.context.ProfileHolder
import com.ruoyi.app.common.Data
import com.ruoyi.app.common.Fail
import com.ruoyi.app.common.Ok
import com.ruoyi.app.common.messageRedisKey
import com.ruoyi.app.service.LoginApiService
import com.ruoyi.app.service.UserApiService
import com.ruoyi.back.domain.AppUserSetting
import com.ruoyi.back.domain.ChannelFunction
import com.ruoyi.back.domain.ChannelManager
import com.ruoyi.back.domain.Function
import com.ruoyi.back.mapper.AppUserSettingMapper
import com.ruoyi.back.service.AppUserService
import com.ruoyi.back.service.ChannelFunctionService
import com.ruoyi.back.service.ChannelManagerService
import com.ruoyi.back.service.FunctionService
import com.ruoyi.common.core.redis.RedisCache
import io.swagger.annotations.Api
import io.swagger.annotations.ApiModel
import io.swagger.annotations.ApiModelProperty
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("api/v1Api")
@Api(tags = ["8月最新改动功能"])
class V1ApiController {

    @Autowired
    private lateinit var functionService: FunctionService

    @Autowired
    private lateinit var channelManagerService: ChannelManagerService

    @Autowired
    private lateinit var channelFunctionService: ChannelFunctionService

    @Autowired
    private lateinit var appUserService: AppUserService

    @Autowired
    private lateinit var loginApiService: LoginApiService

    @Autowired
    private lateinit var redisCache: RedisCache

    @Autowired
    private lateinit var appUserSettingMapper: AppUserSettingMapper

    @Autowired
    private lateinit var userApiService: UserApiService

    @ApiOperation("是否需要实名认证")
    @GetMapping("booleanRealNameAuthentication")
    fun booleanRealNameAuthentication(channelCode: String): Data<Boolean> {

        var result = false
        channelManagerService.getOne(
            KtQueryWrapper(ChannelManager::class.java)
                .eq(ChannelManager::code, channelCode)
        )
            ?.let { channelManager ->

                functionService.getOne(
                    KtQueryWrapper(Function::class.java)
                        .eq(Function::name, "实名制")
                )
                    ?.let { function ->

                        channelFunctionService.getOne(
                            KtQueryWrapper(ChannelFunction::class.java)
                                .eq(ChannelFunction::channelId, channelManager.id)
                                .eq(ChannelFunction::functionId, function.id)
                        )
                            ?.let {

                                appUserService.getById(ProfileHolder.getProfile().id)
                                    ?.let { appUser ->
                                        result = appUser.phoneNum == null
                                    }
                            }
                    }
            }

        return Ok("获取结果成功", result)
    }


    @ApiOperation("修改用户首次安装app时间")
    @GetMapping("updateUserFirstInstallationData")
    fun updateUserFirstInstallationData(firstInstallationData: String): Data<Boolean> =
        userApiService.updateUserFirstInstallationData(firstInstallationData)

    @ApiOperation("发送短信验证码")
    @GetMapping("sendSms/{phone}")
    fun sendSms(@PathVariable phone: String): Data<String> = loginApiService.sendSms(phone)


    @ApiModel("实名验证参数")
    data class RealNameAuthentication(

        @ApiModelProperty("手机号码")
        var phoneNum: String? = null,

        @ApiModelProperty("验证码")
        var code: String? = null
    )

    @ApiOperation("提交实名验证")
    @PostMapping("submitRealNameAuthentication")
    fun submitRealNameAuthentication(realNameAuthentication: RealNameAuthentication): Data<Boolean> =
        redisCache.getCacheObject<String>(messageRedisKey(realNameAuthentication.phoneNum!!))?.run {
            ObjectUtil.equals(this, realNameAuthentication.code).takeIf { it }?.run {
                Ok("实名验证成功", appUserService.getById(ProfileHolder.getProfile().id)?.run {
                    appUserService.updateById(this.apply {
                        phoneNum = realNameAuthentication.phoneNum
                    })
                })
            } ?: run { Fail(201, "短信验证码不一致!") }
        } ?: run { Fail(202, "短信验证码不存在!") }


    @ApiOperation("用户水印设置")
    @PostMapping("userWatermarkSetting")
    fun userWatermarkSetting(appUserSetting: AppUserSetting): Data<Boolean> =
        appUserSettingMapper.selectOne(
            KtQueryWrapper(AppUserSetting::class.java)
                .eq(AppUserSetting::userId, ProfileHolder.getProfile().id)
        )?.run {
            Ok("设置成功", appUserSettingMapper.updateById(this.apply {
                appUserSetting.aiWatermark?.let {
                    this.aiWatermark = it
                }
                appUserSetting.softWatermark?.let {
                    this.softWatermark = it
                }
            }) > 0)
        } ?: run {
            Ok("设置成功", appUserSettingMapper.insert(AppUserSetting().apply {
                userId = ProfileHolder.getProfile().id.toLong()
                softWatermark = appUserSetting.softWatermark ?: false
                aiWatermark = appUserSetting.aiWatermark ?: false
            }) > 0)
        }

    @ApiOperation("获取用户水印设置结果")
    @GetMapping("getUserWatermarkSetting")
    fun getUserWatermarkSetting(): Data<AppUserSetting> =
        appUserSettingMapper.selectOne(
            KtQueryWrapper(AppUserSetting::class.java)
                .eq(AppUserSetting::userId, ProfileHolder.getProfile().id)
        )
            ?.run {
                Ok("获取成功", this)
            } ?: run {
            Ok("获取成功", AppUserSetting().apply {
                aiWatermark = false
                softWatermark = false
            })
        }
}